package cn.xuexiluxian.open.framework.configuration;

import cn.xuexiluxian.open.common.constant.Constants;
import cn.xuexiluxian.open.framework.interceptor.DemonstrationInterceptor;
import cn.xuexiluxian.open.framework.interceptor.RepeatSubmitInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 资源配置
 */
@Slf4j
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {
    @Value("${common.uploadPath}")
    private String uploadDir;

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;
    @Autowired
    private DemonstrationInterceptor demonstrationInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File file = new File(uploadDir);
        if (!file.exists()) {
            log.error("资源目录不存在或设置错误！");
        }
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
                .addResourceLocations("file:" + uploadDir + Constants.RESOURCE_PREFIX + "/")
                .setCachePeriod(31556926);
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
        registry.addInterceptor(demonstrationInterceptor).addPathPatterns("/**");
    }

}
